package com.yzy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzy.entity.*;
import com.yzy.mapper.GoodsMapper;
import com.yzy.mapper.OrderMapper;
import com.yzy.mapper.UserMapper;
import com.yzy.util.Message;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private UserMapper userMapper;

    public List<Goods> search(Integer downloadUserId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("download_user_id",downloadUserId);
        List<Order> list = list(wrapper);
        List<Goods> goodsList = new ArrayList<>();
        List<Integer> idList = new ArrayList<>();
        for(Order order : list){
            idList.add(order.getGoodsId());
        }

        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.in("id",idList);

        return goodsMapper.selectList(goodsQueryWrapper);
    }

    /**
     * @description 创建订单
     * @param userId 用户id
     * @param goodsId 商品id
     * @return java.lang.String
     * @author mgl
     * @date 2023/8/12 16:53
     */
    public String createOrder(Integer userId, Integer goodsId) {
        Order order = new Order();
        Goods byId = goodsMapper.selectById(goodsId);
        if (byId == null) return Message.GOODS_NOT_EXIT; //商品不存在或下架
        User user = userMapper.selectById(userId);
        if (user == null) return Message.USER_NOT_EXIT; //用户非法
        if (user.getMoney() < byId.getPrice())
            return Message.USER_MONEY_NOT_ENOUGH; //余额不足
        //查询用户是否已经购买了这个商品
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",goodsId);
        wrapper.eq("download_user_id",userId);
        if (orderMapper.selectCount(wrapper) > 0)
            return Message.USER_ALREADY_BOUGHT;
        //封装订单对象
        order.setStatus(1);
        order.setGoodsId(goodsId);
        order.setPayment(byId.getPrice());
        order.setUploadUserId(byId.getUploadUserId());
        order.setDownloadUserId(userId);
        order.setBuyTime(new Date());
        //插入数据库
        orderMapper.insert(order);
        //订单成功插入表中后，需要给用户的余额相应减少
        user.setMoney(user.getMoney() - byId.getPrice());
        userMapper.updateById(user);
        return Message.ORDER_CREATE_SUCCESS;
    }
}




